package utils;

import java.util.*;
import java.util.stream.Collectors;

public class CollectionUtils {

    public static boolean isNotEmpty(Collection<?> collection) {
        return collection != null && !collection.isEmpty();
    }

    public static boolean isEmpty(Collection<?> collection) {
        return !isNotEmpty(collection);
    }

    public static <T> ArrayList<T> toArrayList(T... array) {
        ArrayList<T> ret = new ArrayList<>();

        if (array != null) {
            for (T t : array) {
                ret.add(t);
            }
        }

        return ret;
    }

    /**
     * 计算差集
     *
     * @param list
     * @param list2
     * @param <T>
     * @return
     */
    public static <T> List<T> diff(List<T> list, List<T> list2) {
        if (list == null) {
            return Collections.EMPTY_LIST;
        }

        if (list2 == null) {
            return new ArrayList<>(list);
        }

        List<T> ret = new ArrayList<>();
        for (T t : list) {
            if (!list2.contains(t)) {
                ret.add(t);
            }
        }

        return ret;
    }

    public static void removeLast(List<?> list) {
        list.remove(list.size() - 1);
    }

    public static void removeFirst(List<?> list) {
        list.remove(0);
    }

    public static <T> List<T> removeNull(List<T> list) {
        List<T> result = new ArrayList<T>();
        for (T t : list) {
            if (t != null) {
                result.add(t);
            }
        }

        return result;
    }

    public static List<Object> nullToEmpty(List<Object> result) {
        if (result == null) {
            return Collections.EMPTY_LIST;
        }

        return result;
    }

    public static <T> void addElementRepeatedly(List<T> list, T element, int count) {
        for (int i = 0; i < count; i++) {
            list.add(element);
        }
    }

    public static List removeAfter(List list, int index) {

        for (int j = list.size(); j > index; j--) {
            list.remove(j - 1);
        }
        return list;

    }

    public static <T> List<T> filter(List<T> source, java.util.function.Predicate<? super T> predicate) {
        return source.stream().filter(predicate).collect(Collectors.toList());
    }

    public static <T> T findFirst(List<T> source, java.util.function.Predicate<? super T> predicate) {
        for (T t : source) {
            if (predicate.test(t)) {
                return t;
            }
        }
        return null;
    }

    public static <T, R> List<R> map(List<T> source, java.util.function.Function<T, R> function) {
        return source.stream().map(function).collect(Collectors.toList());
    }

    public static <T> T last(List<T> value) {
        return value.get(value.size() - 1);
    }

}
